package com.tailyou.hms.firstapp.act;

import android.animation.ObjectAnimator;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.view.View;
import android.view.animation.LinearInterpolator;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import com.tailyou.hms.firstapp.R;
import com.tailyou.hms.firstapp.service.PlayService;

import java.util.Timer;
import java.util.TimerTask;

public class PlayerActivity extends AppCompatActivity {

    private PlayService.MyBinder myBinder;
    private Timer mTimer;
    //播放音乐旋转动画
    private ObjectAnimator objectAnimator;
    private ImageView musicPic;
    private ImageView ivPlay;
    private TextView tvTime;
    private TextView tvPrg;
    private SeekBar msb;
    //标记当前是暂停还是播放
    private boolean isPlay;

    //绑定Service时建立的连接
    private ServiceConnection mServiceConnection = new ServiceConnection() {
        /**
         * 绑定成功时的回调
         * @param name
         * @param service
         */
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            myBinder = (PlayService.MyBinder) service;
            if (myBinder.isPlaying()) {
                doPlay();
                updateMusicTime();
            }
        }

        /**
         * 取消绑定的回调
         * @param name
         */
        @Override
        public void onServiceDisconnected(ComponentName name) {
            myBinder.close();
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_player);
        initView();
        bindService();
        initTimer();
        initAnimation();
    }

    /**
     * 初始化UI
     */
    private void initView() {
        musicPic = findViewById(R.id.music_pic);
        ivPlay = findViewById(R.id.play);
        tvTime = findViewById(R.id.tv_music_time);
        tvPrg = findViewById(R.id.tv_play_prg);
        msb = findViewById(R.id.msb);
        //监听SeekBar进度变化
        msb.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                //如果时人为手动拖拽改变进度，则通知音乐播放服务更改播放进度
                if (fromUser) {
                    myBinder.setPosition(progress);
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                //暂时不用，开始拖拽时回调
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                //暂时不用，结束拖拽时回调
            }
        });
        ivPlay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isPlay) {
                    doPause();
                } else {
                    doPlay();
                }
            }
        });
    }

    /**
     * 开始播放/恢复播放
     */
    private void doPlay() {
        isPlay = true;
        ivPlay.setImageResource(R.mipmap.play_btn_pause_prs);
        objectAnimator.start();
        if (myBinder.getPosition() == 0) {
            myBinder.play();
        } else {
            myBinder.replay();
        }
    }

    /**
     * 暂停播放
     */
    private void doPause() {
        isPlay = false;
        ivPlay.setImageResource(R.mipmap.play_btn_play);
        objectAnimator.pause();
        myBinder.pause();
    }

    /**
     * 初始化定时器任务，每秒更新一下播放进度
     */
    private void initTimer() {
        mTimer = new Timer();
        mTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        updateMusicTime();
                    }
                });
            }
        }, 1000, 1000);
    }

    /**
     * 初始化旋转动画，用于播放音乐时，碟片的转动
     */
    private void initAnimation() {
        objectAnimator = ObjectAnimator.ofFloat(musicPic, "rotation", 0f, 360f);
        objectAnimator.setDuration(24000);// 持续24秒
        LinearInterpolator mLinearInterpolator = new LinearInterpolator();
        objectAnimator.setInterpolator(mLinearInterpolator);// 设置动画匀速
        objectAnimator.setRepeatCount(ObjectAnimator.INFINITE);// 无限播放
        objectAnimator.setRepeatMode(ObjectAnimator.RESTART);// 重复播放模式
    }

    /**
     * 更新时间，包括歌曲总时长和当前播放进度
     */
    private void updateMusicTime() {
        long duration = myBinder.getMusicDuration();
        msb.setMax((int) duration);
        tvTime.setText(String.format("%02d:%02d", duration / 1000 / 60, duration / 1000 % 60));
        long position = myBinder.getPosition();
        msb.setProgress((int) position);
        tvPrg.setText(String.format("%02d:%02d", position / 1000 / 60, position / 1000 % 60));
    }

    /**
     * 绑定PlayService
     */
    private void bindService() {
        Intent intent = new Intent(this, PlayService.class);
        bindService(intent, mServiceConnection, BIND_AUTO_CREATE);
    }

}